package io

import (
	"gitee.com/injoyai/goutil/maps"
	"io"
)

func NewPool() *Pool {
	return &Pool{conn: maps.NewSafe()}
}

type Pool struct {
	conn  *maps.Safe //客户端连接池
	key   string     //连接池标识
	debug bool       //调试模式
}

func (this *Pool) SetKey(s string) {
	this.key = s
}

func (this *Pool) GetKey() string {
	return this.key
}

func (this *Pool) Debug(b ...bool) {
	this.debug = !(len(b) > 0 && !b[0])
}

func (this *Pool) SetConn(key string, conn io.ReadWriteCloser) {
	if conn == nil {
		return
	}
	i := this.conn.GetInterface(key)
	if i != nil {
		i.(io.ReadWriteCloser).Close()
	}
	this.conn.Set(key, conn)
}

func (this *Pool) GetConn(key string) io.ReadWriteCloser {
	i := this.conn.GetInterface(key)
	if i == nil {
		return nil
	}
	return i.(io.ReadWriteCloser)
}

func (this *Pool) CloseConn(key string) {
	i := this.GetConn(key)
	if i != nil {
		i.Close()
	}
	this.DelConn(key)
}

func (this *Pool) DelConn(key string) {
	this.conn.Del(key)
}
